package loadBalancer;

import cn.hutool.core.collection.CollUtil;
import model.ServiceInfo;

import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 随机负载均衡器
 */
public class RandomBalancer implements LoadBalance{
    /**
     * 随机数类.nextInt生成[0,bound)之间的整数
     */
    private static final Random random = new Random();
    public ServiceInfo selectServiceFromList(Map<String,Object> requestParams, List<ServiceInfo> serviceInfoList){
        //为空则返回null，说明没有可用服务
        if(CollUtil.isEmpty(serviceInfoList))return null;

        //若只有一个服务，直接取第一个
        int size = serviceInfoList.size();
        if(size == 1)return serviceInfoList.get(0);
        return serviceInfoList.get(random.nextInt(size));
    }
}
